#pragma once

#include <iostream>
#include "log.hpp"
#include "errno.hpp"
#include <sys/epoll.h>
#include <unistd.h>
#define BLOCK -1
static const int defaultfd = -1;
static const int defaultsize = 128;
class Epoll{
public:
    Epoll() :_epollfd(defaultfd)
    {
    }
    ~Epoll()
    {
        if(_epollfd != defaultfd)   close(_epollfd); 
    }
public:
    void Create(){
        _epollfd = epoll_create(defaultsize);
        logmessage(DEBUG,"epollfd:%d",_epollfd);
        if(_epollfd == -1){
            logmessage(FATAL,"epoll create faild,errocode:%d,errostr:%s",errno,strerror(errno));
            exit(EPOLLCREATEERRO);
        }
        logmessage(NORMAL,"epoll create succuss");
    }
    void AddEvent(int fd,uint32_t events){
        struct epoll_event ep;
        ep.events = events;
        ep.data.fd = fd;
        if(epoll_ctl(_epollfd,EPOLL_CTL_ADD,fd,&ep) == -1 ){
            logmessage(DEBUG,"epollfd:%d,fd:%d",_epollfd,fd);
            logmessage(ERROR,"AddEvents faild,errocode:%d,errostr:%s",errno,strerror(errno));
        }else{
            logmessage(NORMAL,"AddEvents succuss");
        }
    }
    void DelEvent(int fd){
        struct epoll_event ep;
        if(epoll_ctl(_epollfd,EPOLL_CTL_DEL,fd,&ep) == -1 ){
            logmessage(ERROR,"DelEvents faild,errocode:%d,errostr:%s",errno,strerror(errno));
        }else{
            logmessage(NORMAL,"DelEvents succuss,client quit");
        }
    }
    void ModEvent(int fd,uint32_t events){
        struct epoll_event ep;
        ep.events = events;
        ep.data.fd = fd;
        if(epoll_ctl(_epollfd,EPOLL_CTL_MOD,fd,&ep) == -1 ){
            logmessage(DEBUG,"epollfd:%d,fd:%d",_epollfd,fd);
            logmessage(ERROR,"MovEvents faild,errocode:%d,errostr:%s",errno,strerror(errno));
        }else{
            logmessage(NORMAL,"MovEvents succuss");
        }
    }
    int Wait(struct epoll_event* events,int maxevents){
        int n = epoll_wait(_epollfd,events,maxevents,BLOCK);
        if(n == -1){
            logmessage(ERROR,"epoll wait faild,errocode:%d,errostr:%s",errno,strerror(errno));
        }else{
            logmessage(NORMAL,"epoll wait succuss");
        }
        return n;
    }

private:
    int _epollfd;
};